package com.easonji.attendance.controller;



import com.easonji.admin.service.IUserUserPostService;
import com.easonji.common.base.controller.BaseController;

import com.easonji.core.annotion.Permission;
import com.easonji.core.log.LogObjectHolder;
import com.easonji.common.base.query.BaseQuery;
import com.easonji.common.base.response.Response;
import com.easonji.common.base.response.enums.ResponseEnum;
import com.easonji.common.util.StringUtils;

import com.easonji.attendance.service.IRecordService;
import com.easonji.attendance.model.Record;

import com.easonji.core.shiro.ShiroUser;
import com.easonji.core.shiro.util.ShiroUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.validation.BindingResult;
import org.springframework.ui.Model;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.*;


/**
 * <p>
 * 补卡 前端控制器
 * </p>
 *
 * @author easonji
 * @since 2018-10-05
 */
@Controller
@RequestMapping("/attendance/record")
public class RecordController extends BaseController {


    /**
    * 补卡页面前缀
    */
    private final static String PREFIX = "attendance/record/";

    @Resource
    private IRecordService recordService;

    @Resource
    private IUserUserPostService userUserPostService;

    /**
    * 跳转到补卡首页
    */
    @Permission
    @GetMapping("")
    public String index() {
        return PREFIX + "record";
    }

    /**
    * 查询补卡列表
    */
    @ResponseBody
    @PostMapping("/list")
    public Object queryList(BaseQuery baseQuery) {
        Object result = recordService.queryList(baseQuery);
        return result;
    }

    /**
    * 跳转到添加补卡页面
    */
    @Permission
    @GetMapping("/to_add")
    public String toAdd(Model model) {
        return PREFIX + "record_edit";
    }

    /**
     * 跳转到添加补卡页面
     */
    @Permission
    @GetMapping("/batch/to_add")
    public String toBatchAdd(Model model) {
        ShiroUser shiroUser = ShiroUtils.getUser();
        Object result = userUserPostService.queryListByPid(shiroUser.getUserId());
        model.addAttribute("userComboList",result);
        return PREFIX + "record_batch_edit";
    }

    /**
    * 跳转到修改补卡页面
    */
    @Permission
    @GetMapping("/to_update/{reId}")
    public String toUpdate(@PathVariable Integer reId, Model model) {
        Object result = recordService.queryRowById(reId);
        LogObjectHolder.me().set(result);
        model.addAttribute("record", result);
        return PREFIX + "record_edit";
    }

    /**
    * 新增补卡
    */
    @ResponseBody
    @Permission
    @PostMapping("/save")
    public Response add(@Valid Record record, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return failure(bindingResult);
        }

        ShiroUser shiroUser = ShiroUtils.getUser();

        int result = save_pub(record,shiroUser.getUserId());
        if (result == 0) {
            return failure(ResponseEnum.DATABASE_ERROR);
        }
        return success(ResponseEnum.SAVE_SUCCESS);
    }

    /**
     * 批量新增补卡
     */
    @ResponseBody
    @Permission
    @PostMapping("/batch/save")
    public Response batch_add(@Valid  Record record,@RequestParam(value = "reUsers[]", required = false) String[] reUsers, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return failure(bindingResult);
        }

        int result = 0;

        for(String reUser :reUsers){
            result = save_pub(record,Integer.parseInt(reUser));
        }

        if (result == 0) {
            return failure(ResponseEnum.DATABASE_ERROR);
        }
        return success(ResponseEnum.SAVE_SUCCESS);
    }

    /**
     * 保存公共方法
     * @param record
     * @param userId
     * @return
     */
    private Integer save_pub(Record record,Integer userId){
        ShiroUser shiroUser = ShiroUtils.getUser();
        record.setReUser(userId);
        record.setReCreateUser(shiroUser.getUserId());
        record.setReCreateDate(new Date());
        record.setReUpdateUser(shiroUser.getUserId());
        record.setReUpdateDate(new Date());
        record.setReState(0);

        //当前员工
        Integer userInt = shiroUser.getUserId();

        Integer otNextAuditor = null;

        List<Map<String,Integer>> Auditors = new ArrayList<>();

        //判断职务是员工 则增加线长审核
        if(shiroUser.getPostId()==3){
            //查询审核人的 ID
            userInt = userUserPostService.queryUserPidByuserIdandpost(userInt,3);
            otNextAuditor = userInt;
            Map<String,Integer> map  = new HashMap<>();
            map.put("user",userInt);
            map.put("post",2);
            Auditors.add(map);
        }

        //员工和线长都需要主管审核
        if(shiroUser.getPostId()==3 || shiroUser.getPostId()==2){
            //查询审核人的 ID
            userInt = userUserPostService.queryUserPidByuserIdandpost(userInt,2);
            if(otNextAuditor==null){
                otNextAuditor = userInt;
            }
            Map<String,Integer> map  = new HashMap<>();
            map.put("user",userInt);
            map.put("post",1);
            Auditors.add(map);
        }

        record.setReNextAuditor(otNextAuditor);


        int result = recordService.save(record,Auditors);
        return result;
    }

    /**
    * 修改补卡
    */
    @ResponseBody
    @Permission
    @PostMapping("/update")
    public Response update(@Valid Record record, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return failure(bindingResult);
        }
        int result = recordService.update(record);
        if (result == 0) {
            return failure(ResponseEnum.DATABASE_ERROR);
        }
        return success(ResponseEnum.UPDATE_SUCCESS);
    }

    /**
    * 删除补卡
    */
    @ResponseBody
    @Permission
    @PostMapping("/remove")
    public Response remove(@RequestParam Integer reId) {
        if (StringUtils.isEmpty(reId)) {
            return failure(ResponseEnum.PARAMETER_ERROR);
        }
        int result = recordService.delete(reId);
        if (result == 0) {
            return failure(ResponseEnum.DATABASE_ERROR);
        }
        return success(ResponseEnum.REMOVE_SUCCESS);
    }

}
